package jgl.vajra.management.manager;

import android.content.Context;
import android.text.TextUtils;

import androidx.fragment.app.FragmentActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jgl.vajra.management.bean.LoginInfoBean;
import jgl.vajra.management.bean.UserInfo;
import jgl.vajra.management.bean.VersionUpdateBean;
import jgl.vajra.management.constant.Constant;
import jgl.vajra.management.event.LoginOutEvent;
import jgl.vajra.management.utils.RandomUtils;
import jgl.vajra.management.widget.base.BaseApplication;
import jgl.vajra.management.widget.dialogfragment.MessageDialogFragment;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.SPManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.management.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.management.widget.utils.AppUtils;
import jgl.vajra.management.widget.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

public class AccountManager {


    private MessageDialogFragment messageDialogLoginFragment;

    public String getUserRealPhone() {
        return userRealPhone;
    }

    public String userRealPhone;


    private static class AccountManagerSingleton {
        private static final AccountManager INSTANCE = new AccountManager();

    }

    public static AccountManager getInstance() {
        return AccountManager.AccountManagerSingleton.INSTANCE;
    }

    private AccountManager() {
    }

    private UserInfo getUserInfoFromCache(Context context) {
        String userInfo = SPManager.UserData.getUserInfo(context);
        if (TextUtils.isEmpty(userInfo)) {
            return new UserInfo();
        }
        return JSONObject.parseObject(userInfo, UserInfo.class);
    }

    public void setUserRealPhone(String phone) {
        this.userRealPhone = phone;
    }

    public void setUserInfo(Context context, UserInfo userInfo) {
        BaseApplication.setUserInfo(userInfo);
        String userInfoData = JSON.toJSONString(userInfo);
        SPManager.UserData.saveUserInfo(context, userInfoData);
    }

    public void setUserInfo(Context context, String userJsonData) {
        UserInfo userInfo = JSONObject.parseObject(userJsonData, UserInfo.class);
        setUserInfo(context, userInfo);
        SPManager.UserData.saveUserInfo(context, userJsonData);
    }

    public UserInfo getUserInfo(Context context) {
        UserInfo userInfo = BaseApplication.getUserInfo();
        if (userInfo == null) {
            userInfo = getUserInfoFromCache(context);
            BaseApplication.setUserInfo(userInfo);
        }
        return userInfo;
    }


    public void saveLoginData(Context context, LoginInfoBean loginInfoBean) {
       // loginInfoBean.tokenTime = System.currentTimeMillis();
        BaseApplication.setLoginData(loginInfoBean);
        String loginInfoBeanString = JSON.toJSONString(loginInfoBean);
        SPManager.UserData.saveLoginData(context, loginInfoBeanString);
    }

    public LoginInfoBean getLoginData(Context context) {
        LoginInfoBean loginInfoBean = BaseApplication.getLoginData();
        if (loginInfoBean == null) {
            loginInfoBean = getLoginDataFromCache(context);
            BaseApplication.setLoginData(loginInfoBean);
        }
        return loginInfoBean;
    }

    private LoginInfoBean getLoginDataFromCache(Context context) {

        String loginInfoBean = SPManager.UserData.getLoginData(context);
        if (TextUtils.isEmpty(loginInfoBean)) {
            return new LoginInfoBean();
        }
        return JSONObject.parseObject(loginInfoBean, LoginInfoBean.class);
    }

    public String getUserId() {
        return getUserId(UIUtils.getContext());
    }

    public String getUserId(Context context) {
        return getUserInfo(context).uniqueId;
    }

    public boolean isLogin() {
        return isLogin(UIUtils.getContext());
    }

    public boolean isLogin(Context context) {
       /* UserInfo userInfo = getUserInfo(context);

        return !TextUtils.isEmpty(userInfo.uniqueId);*/
        LoginInfoBean loginData = getLoginData(context);
        return !TextUtils.isEmpty(loginData.accessToken);
    }



    public void logout(Context context) {
        if (!AccountManager.getInstance().isLogin()) return;
        clearUserInfo(context);
        EventBus.getDefault().post(new LoginOutEvent());
        setUserRealPhone("");
        JPushInterface.cleanTags(UIUtils.getContext(), 10086);
        JPushInterface.clearAllNotifications(UIUtils.getContext());
        JPushInterface.deleteAlias(UIUtils.getContext(), 10087);
        JPushInterface.resumePush(UIUtils.getContext());
    }

    public void clearUserInfo(Context context) {
        if (!AccountManager.getInstance().isLogin()) return;
        BaseApplication.setUserInfo(null);
        BaseApplication.setLoginData(null);
        SPManager.UserData.saveUserInfo(context, "");
        SPManager.UserData.saveLoginData(context, "");

    }


    boolean isRefreshToken = false;

    public void refreshToken(final Context context) {
        if (true) return;
        if (!AccountManager.getInstance().isLogin()) return;
        if (isRefreshToken) return;
        isRefreshToken = true;
        RetrofitJsonManager.getInstance().getApiService().refreshToken().compose(RxJavaHttpManager.<LoginInfoBean>applyTransformer()).subscribe(new ProgressObserver<LoginInfoBean>(false, false, false, null) {
            @Override
            public void _onNext(LoginInfoBean loginInfoBean) {
                isRefreshToken = false;
                saveLoginData(context, loginInfoBean);

            }

            @Override
            public void _onError(String errorMessage, int errorCode) {
                super._onError(errorMessage, errorCode);
                isRefreshToken = false;

            }
        });

    }

    int refreshTokenCount = 1;

    public void refreshTokenCount(final Context context) {
        if (true) return;
        if (!AccountManager.getInstance().isLogin()) return;
        if (refreshTokenCount > 5) return;
        if (isRefreshToken) return;
        isRefreshToken = true;
        RetrofitJsonManager.getInstance().getApiService().refreshToken().compose(RxJavaHttpManager.<LoginInfoBean>applyTransformer()).subscribe(new ProgressObserver<LoginInfoBean>(false, false, false, null) {
            @Override
            public void _onNext(LoginInfoBean loginInfoBean) {
                isRefreshToken = false;
                refreshTokenCount = 1;
                saveLoginData(context, loginInfoBean);

            }

            @Override
            public void _onError(String errorMessage, int errorCode) {
                super._onError(errorMessage, errorCode);
                isRefreshToken = false;
                refreshTokenCount++;
                refreshTokenCount(context);

            }
        });

    }

    boolean isGetMessageCount = false;
    boolean isShowLoginDialog = false;

    public synchronized void toDialogLoginHomeActivity() {

    }

    public void getNetUserInfo(final FragmentActivity fragmentActivity, LoginInfoBean loginInfoBean) {
        getNetUserInfo(fragmentActivity, loginInfoBean, true);
    }

    public void getNetUserInfo(final FragmentActivity fragmentActivity, LoginInfoBean loginInfoBean, boolean isShowLoading) {


    }

    public void getNetUserInfo(final FragmentActivity fragmentActivity, LoginInfoBean loginInfoBean, boolean isRegister, int parentType, String phone) {


    }

    public void getVersionUpdate(FragmentActivity activity) {
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数
        map.put("id", Constant.USER_TYPE);
        RetrofitJsonManager.getInstance().getApiService().getVersionUpdate(map).compose(RxJavaHttpManager.applyTransformer()).subscribe(new ProgressObserver<VersionUpdateBean>(false, false, false, null) {
            @Override
            public void _onNext(VersionUpdateBean versionUpdateBean) {
                int version =Integer.parseInt(versionUpdateBean.version.replace(".","")) ;
                int currentVersion =Integer.parseInt( AppUtils.getAppInfo().getVersionName().replace(".",""));

                if (version <= currentVersion) {
                    return;
                }
                FragmentManager.getVersionUpdateDialogFragment(activity, versionUpdateBean);
            }
        });
    }
}
